package com.xjgc.ws.util;

import com.xjgc.common.config.DbConn;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;

/**
 * 
 * @author jjg-pc
 *实现单表的XML数据解析并组装成SQL语句执行
 */
public class test {
	
	String mkId = null;
	
	/**
	 * 分包处理模式，需考虑分包操作
	 * 解析报文xml
	 * 根据联合主键删除操作数据del
	 * 执行插入操作sql
	 * 返回执行结果：操作结果记录
	 * @param xml
	 * @return
	 * @throws SQLException 
	 */
	public String tsmsup(String xml) throws SQLException{
		
		String rs = null;
		PreparedStatement delPst = null;
		PreparedStatement inPst = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String opTime = sdf.format(new Date());
		
		//定义执行SQL脚本
		String delSql = "delete from t_smsup where id=?"; //删除SQL
		String inSql = "insert into t_smsup(id,head,body1,body2,time)values(?,?,?,?,?)";  //插入SQL
		
		//创建数据库连接
		DbConn db = new DbConn();
		delPst = db.getConnetion().prepareStatement(delSql);
		inPst = db.getConnetion().prepareStatement(inSql);
		int count=0;
		
		//解析xml文件
		Document doc = null;
		try {
			doc = DocumentHelper.parseText(xml);
			Element root = doc.getRootElement();
			Iterator<?> it = root.elementIterator();
			
			
			while(it.hasNext()) {
				
				Element element = (Element) it.next();
				
				delPst.setInt(1, Integer.parseInt(element.attributeValue("id")));
				
				inPst.setInt(1, Integer.parseInt(element.attributeValue("id")));
				inPst.setString(2, element.elementText("title"));
				inPst.setString(3, element.elementText("title"));
				inPst.setString(4, element.elementText("author"));
				inPst.setString(5, opTime);
				
				System.out.println("*********************** mkId= "+mkId+"     "+element.attributeValue("id"));
				if(!element.attributeValue("id").equals(mkId)){
					//删除现有数据
					delPst.executeUpdate();
				}
				//设置业务id
				mkId = element.attributeValue("id");
				
				//插入更新数据
				int row = inPst.executeUpdate();
				if(row>0) {
					count++;
				}
			}
			if (count>0) {
				rs = " ************  t_smsup: "+count+"  条记录执行成功！！！";
			}
		} catch (DocumentException e1) {
			rs="xml文件接收失败！！！";
			e1.printStackTrace();
		}
		//关闭连接
		delPst.close();
		inPst.close();
		db.closeCn();
		return rs;
	}
}
